<?php
require_once('ObjectClasses/Post.php');

class PortfolioGalleryHandler{
	private $db = NULL;
	public function __construct(DBConnection $db){
		$this->db = $db;
	}
	
	public function getPicturePost($id){
		$sql = "SELECT *, IFNULL((SELECT COUNT(*) as noc FROM postcomment WHERE postcomment.postid = post.postid GROUP BY post.postid), '0') as noc FROM post WHERE postId = ? ORDER BY post.pdate DESC";
		$stmt = $this->db->Prepare($sql);
		
		$stmt->bind_param('i', $id);

		$stmt->execute();
		
		$result = $stmt->get_result();
		
		$obj = new Post;

		while ($p = $result->fetch_assoc()) {
			
			$obj->postTitle($p['title']);
			$obj->postText($p['ptext']);
			$obj->postDate($p['pdate']);
			$obj->postId($p['postid']);
			$obj->postNumberOfComments($p['noc']);
			$obj->postComments(self::getPostComments($p['postid']));
			if($p['pictureSrc'] != NULL){
				$obj->postPicture($p['pictureSrc']);
			}
			
		}
		
		
		
		return $obj;
	}
	
	public function getPostComments($pid){
		$sql = "SELECT postcomment.*, user.username FROM postcomment INNER JOIN user ON user.userid = postcomment.userid WHERE postid = ?";
		$stmt = $this->db->Prepare($sql);
		$stmt->bind_param('i', $pid);
		
		$stmt->execute();
		
		$result = $stmt->get_result();
		
		$commentArray = array();

		while ($c = $result->fetch_assoc()) {
			$obj = new Comment;
			$obj->commentText($c['commentText']);
			$obj->commentDate($c['commentDate']);
			$obj->commentId($c['postCommentId']);
			$obj->userId($c['userId']);
			$obj->commentUser($c['username']);
			array_push($commentArray, $obj);
		}
		
		return $commentArray;
	}
}
?>